package com.along.auth.service;

import com.along.auth.dto.LoginDTO;
import com.along.auth.dto.RegisterDTO;
import com.along.auth.entity.SysUser;
import com.along.auth.mapper.SysUserMapper;
import com.along.utility.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/*
 *@Author: liujinyi
 *@CreateTime: 2025-08-05
 *@Description:
 *@Version: 1.0
 */
@Service
public class AuthService {
    @Autowired
    private SysUserMapper userMapper;

    public String login(LoginDTO loginDTO, HttpServletRequest request) {
        // 使用 Mapper 中的注解方法
        SysUser user = userMapper.selectByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        String encryptedPassword = SecurityUtils.encryptPassword(loginDTO.getPassword());
        if (!encryptedPassword.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        if ("1".equals(user.getStatus())) {
            throw new RuntimeException("账号已停用");
        }

        // 使用 Mapper 中的更新登录信息方法
        userMapper.updateLoginInfo(user.getUserId(), SecurityUtils.getIpAddr(request), new Date());

        return SecurityUtils.createToken(user.getUserId().toString());
    }

    public void register(RegisterDTO registerDTO) {
        if (userMapper.checkUsernameUnique(registerDTO.getUsername()) > 0) {
            throw new RuntimeException("用户名已存在");
        }
        SysUser user = new SysUser();
        user.setUserName(registerDTO.getUsername());
        user.setNickName(registerDTO.getNickName());
        user.setPassword(SecurityUtils.encryptPassword(registerDTO.getPassword()));
        user.setPhonenumber(registerDTO.getPhonenumber());
        user.setEmail(registerDTO.getEmail());
        user.setSex(registerDTO.getSex());
        user.setCreateTime(new Date());

        userMapper.insertUser(user);
    }

//    public SysUser selectUserByUsername(String username) {
//        return userMapper.selectByUsername(username);
//    }
}
